import { modal, select } from 'vue-strap'
import { showMsg, addPromoterRule } from '../../../../vuex/action'

export default {
  name: 'rule-add',
  components: {
    modal: modal,
    'v-select': select
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xAdd: addPromoterRule
    }
  },
  data() {
    return {
      showModal: false,
      rule: {
        securityCode: ['01'],
        operate: ['1'],
        openPrice: '',
        dealPrice: '',
        userRange: ''
      },
      securitySelect: {
        value: {val: '01', label: '国信证券'},
        options: [
          {val: '01', label: '国信证券'},
          {val: '02', label: '长城证券'},
          {val: '12900', label: '华林证券'},
          {val: '16700', label: '港股证券'},
          {val: '19900', label: '中山证券'}
        ]
      },
      operateSelect: {
        value: {val: '1', label: '开户'},
        options: [
          {val: '1', label: '开户'},
          {val: '2', label: '交易'}
        ]
      }
    }
  },
  computed: {
    existOpen() {
      return this.rule.operate.indexOf('1')
    },
    existDeal() {
      return this.rule.operate.indexOf('2')
    },
    price() {
      let priceArr = []
      if (this.rule.openPrice && this.existOpen !== -1) {
        priceArr.push(this.rule.openPrice)
      }
      if (this.rule.dealPrice && this.existDeal !== -1) {
        priceArr.push(this.rule.dealPrice)
      }
      return priceArr
    }
  },
  methods: {
    checkValid() {
      var fields = ['securityCode', 'operate']
      for (var field of fields) {
        if ((this.rule[field] + '').length === 0) {
          this.xShowMsg({
            type: 'danger',
            content: '* 标记的都为必填/选项'
          })
          return false
        }
      }
      if ((this.existOpen !== -1 && !this.rule.openPrice) || (this.existDeal !== -1 && !this.rule.dealPrice)){
        this.xShowMsg({
          type: 'danger',
          content: '* 标记的都为必填/选项'
        })
        return false
      }
      return true
    },
    submit() {
      if (this.checkValid()) {
        this.xAdd({
          securityCodes: this.rule.securityCode.join(),
          operates: this.rule.operate.sort().join(),
          prices: this.price.join(),
          userRange: this.rule.userRange
        })
          .then((data) => {
            this.showModal = false
          })
          .catch((res) => {
            this.xShowMsg({
              type: 'danger',
              content: res.error_msg
            })
          })
      }
    }
  }
}
